from django.shortcuts import render

# Create your views here.
from rest_framework.views import APIView
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from django.http import HttpResponse
from rest_framework.generics import GenericAPIView
from .serializers import RegisterSMSCodeSerializer
from django_redis import get_redis_connection
from rest_framework.response import Response
from rest_framework import status
from random import randint
from libs.yuntongxun.sms import CCP

class ImageCode(GenericAPIView):

    def get(self,request,image_code_id):

        text,image = captcha.generate_captcha()
        redis_conn = get_redis_connection('code')
        redis_conn.setex('img_'+str(image_code_id),120,text)

        return HttpResponse(image,content_type='image/jpeg')

class SMSCodeView(GenericAPIView):

    serializer_class=RegisterSMSCodeSerializer
    def get(self,request,mobile):

        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)

        redis_conn = get_redis_connection('code')
        if redis_conn.get('sms_flag_%s'%mobile):
            return Response(status=status.HTTP_429_TOO_MANY_REQUESTS)
        sms_code = '%06d'%randint(0,999999)
        redis_conn.setex('sms_%s'%mobile,5*60,sms_code)
        redis_conn.setex('sms_flag_%s'%mobile,60,1)
        ccp = CCP()
        ccp.send_template_sms(mobile,[sms_code,5],1)
        return Response({'message':'OK'})